//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import SwiftUI
class HomeOwnViewModel : BaseViewModel {
    @Published var items = [DiaryBean]()
    @Published var status = ""
    @Published var status2 = ""
    @Binding var curDate : Date
    private let CODE_EMPTY = 1234
    
    init(curDate: Binding<Date>, item: HomeTableItem) {
        self._curDate = curDate
        super.init()
        self.addObserve(self, .delDiary) {(selfInstance, bean: DiaryBean) in
            withAnimation {
                if let index = selfInstance.items.firstIndex(where: { $0.objectId == bean.objectId }) {
                    selfInstance.items.remove(at: index)
                }
            }
        }
        self.addObserve(self, .addDiary) { (selfInstance, bean: DiaryBean) in
            //添加数据
            selfInstance.addDiary(bean: bean)
        }
    }
    
    //毫秒
    var curTime: Int64 {
        get {
            if curDate.timeIntervalSince1970 == 0 || TimeUtils.isToday(curDate.timeIntervalSince1970) {
                return  getMillisecond(Date().timeIntervalSince1970)
            }
            return getMillisecond(curDate.timeIntervalSince1970 * 1000)
        }
    }
    
    private var startTime: Int64 {
        get {
            let calendar = Calendar.current
            let date = Date(timeIntervalSince1970: getSecond(time: curTime)) // 假设 curTime 是毫秒，转换为秒
            
            var resultDate: Date
            switch AppStorageManager.shared.dateMode {
            case IDateModeType.MONTH:
                var components = calendar.dateComponents([.year, .month], from: date)
                components.day = 1
                components.hour = 0
                components.minute = 0
                components.second = 0
                components.nanosecond = 0
                resultDate = calendar.date(from: components)!
            case IDateModeType.YEAR:
                var components = calendar.dateComponents([.year], from: date)
                components.month = 1
                components.day = 1
                components.hour = 0
                components.minute = 0
                components.second = 0
                components.nanosecond = 0
                resultDate = calendar.date(from: components)!
            case IDateModeType.DAY:
                var components = calendar.dateComponents([.year, .month, .day], from: date)
                components.hour = 0
                components.minute = 0
                components.second = 0
                components.nanosecond = 0
                resultDate = calendar.date(from: components)!
            }
            return getMillisecond(resultDate.timeIntervalSince1970)// 转换回毫秒
        }
    }
    
    private var endTime: Int64 {
        get {
            let calendar = Calendar.current
            let date = Date(timeIntervalSince1970: getSecond(time: curTime)) // 假设 curTime 是毫秒，转换为秒
            
            var resultDate: Date
            switch AppStorageManager.shared.dateMode {
            case IDateModeType.MONTH:
                var components = calendar.dateComponents([.year, .month], from: date)
                components.day = 1 // 明确设置为该月第一天
                if let startOfMonth = calendar.date(from: components),
                   let dayRange = calendar.range(of: .day, in: .month, for: startOfMonth) {
                    components.day = dayRange.last
                }
                components.hour = 23
                components.minute = 59
                components.second = 59
                components.nanosecond = 999
                resultDate = calendar.date(from: components)!
            case IDateModeType.YEAR:
                var components = calendar.dateComponents([.year], from: date)
                components.month = 12
                components.day = 1 // 明确设置为该月第一天
                if let startOfMonth = calendar.date(from: components),
                   let dayRange = calendar.range(of: .day, in: .month, for: startOfMonth) {
                    components.day = dayRange.last
                }
                components.hour = 23
                components.minute = 59
                components.second = 59
                components.nanosecond = 999
                resultDate = calendar.date(from: components)!
            case IDateModeType.DAY:
                var components = calendar.dateComponents([.year, .month, .day], from: date)
                components.hour = 23
                components.minute = 59
                components.second = 59
                components.nanosecond = 999
                resultDate = calendar.date(from: components)!
            }
            
            return getMillisecond(resultDate.timeIntervalSince1970)// 转换回毫秒
        }
    }
    
    func addDiary(bean: DiaryBean) {
        request{
            let list : [DiaryBean] = [bean]
            try await DiaryExt.dealPicture(list, true)
            return list
        } suc: { (list : [DiaryBean]) in
            if let first = list.first {
                withAnimation {
                    self.status = ""
                    self.items.insert(first, at: 0)
                }
                //添加了日记，则开始检查是否有要回应的日记
                ActiveAiExt.checkDiary()
            }
            
        } fail: {
            showToast($0.message)
        }
        
    }
    
    
    func getData(_ isRefresh: Bool = false, item: HomeTableItem) {
        self.status = ""
        self.status2 = ""
        requestList(isRefresh: isRefresh) {
            let list = try await BackupsManager.shared.getDelegateDiary()?.queryHomeDiary(
                userId: item.id,
                startTime: self.startTime,
                endTime: self.endTime,
                keyword: nil,
                pageNo: self.pageNo,
                pageSize: self.pageSize
            ) ?? []
            try check(!isRefresh || !list.isEmpty) {
                return ServerException(code: self.CODE_EMPTY, message: "没有数据")
            }
            return list
        } suc: { diarys in
            self.status = ""
            self.status2 = ""
            self.items.append(contentsOf: diarys)
        } fail: {
            switch $0.code {
            case self.CODE_EMPTY:
                switch AppStorageManager.shared.dateMode {
                case IDateModeType.DAY:
                    self.status = "您当天还没写日记哦"
                    self.status2 = "每一天都是新的开始，让我们用文字记录这份美好"
                case IDateModeType.MONTH:
                    self.status = "您当月还没写日记哦"
                    self.status2 = "让我们用文字记录这份美好"
                case IDateModeType.YEAR:
                    self.status = "这一整年还没有写日记哦"
                    self.status2 = "让我们用文字记录这份美好"
                }
            default :
                self.status = $0.message
            }
        }
    }
    
    func reset() {
        isInit = false
        items.removeAll()
    }
}
